package com.zwcl.general.burypoint.strategy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Range;
import com.zwcl.common.core.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

/**
 * @Description 月份分表策略
 * @Author tanljs
 * @Date 2020/1/6
 * @Email Alex.tan@wetax.com.cn
 */
@Slf4j
//@Component
public class TimeRangeShardingAlgorithm implements RangeShardingAlgorithm<LocalDateTime> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<LocalDateTime> rangeShardingValue) {
        DateFormat sdf = new SimpleDateFormat("yyyyMM");
        Collection<String> result = new LinkedHashSet<>();
        Range<LocalDateTime> shardingKey = rangeShardingValue.getValueRange();
        log.info(shardingKey.lowerEndpoint().toString()+"|"+shardingKey.upperEndpoint());
        LocalDateTime startTime = DateUtils.firstDayOfMonth(shardingKey.lowerEndpoint().toLocalDate());
        LocalDateTime endTime = DateUtils.firstDayOfMonth(shardingKey.upperEndpoint().toLocalDate());
        Calendar cal = Calendar.getInstance();
        while (startTime.isBefore(endTime)) {
            result.add(rangeShardingValue.getLogicTableName().concat("_").concat(sdf.format(startTime)));
            //设置起时间
            startTime = DateUtils.firstDayOfMonth(startTime.plusMonths(1).toLocalDate());
        }
        log.info("范围数据库======{}", JSONUtil.toJsonStr(result));
        return result;
    }
}
